package cn.springcloud.fix.demo.design.adapter;

import cn.springcloud.fix.demo.design.adapter.adapter.AnnotationHandlerAdapter;
import cn.springcloud.fix.demo.design.adapter.adapter.HandlerAdapter;
import cn.springcloud.fix.demo.design.adapter.adapter.HttpHandlerAdapter;
import cn.springcloud.fix.demo.design.adapter.adapter.SimpleHandlerAdapter;
import cn.springcloud.fix.demo.design.adapter.controller.SimpleController;

import java.util.ArrayList;
import java.util.List;

/**
 * 适配器模式
 */
public class DispatchServlet {

    private static List<HandlerAdapter> handlerAdapters = new ArrayList<>();

    static {
        handlerAdapters.add(new AnnotationHandlerAdapter());
        handlerAdapters.add(new HttpHandlerAdapter());
        handlerAdapters.add(new SimpleHandlerAdapter());
    }

    private static HandlerAdapter getHandler(Object controller) {
        for (HandlerAdapter adapter : handlerAdapters) {
            if (adapter.supports(controller)) {
                return adapter;
            }
        }
        return null;
    }

    public static void main(String[] args) {
        SimpleController controller = new SimpleController();
        //得到对应适配器
        HandlerAdapter adapter = getHandler(controller);
        if (adapter != null) {
            //通过适配器执行对应的controller对应方法
            adapter.handle(controller);
        }
    }
}
